package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;

import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String trackMsg, Message message, Channel channel){
        try {
            //获取到数据
            if (!StringUtils.isEmpty(trackMsg)){
                //进行数据转换
                TrackStatMqVo trackStatMqVo = JSON.parseObject(trackMsg, TrackStatMqVo.class);
                //防止消息重复消费
                Boolean result = redisTemplate.opsForValue().setIfAbsent(trackStatMqVo.getBusinessNo(),1,3, TimeUnit.MINUTES);
                try {
                    if (result){
                        trackInfoService.updateTrackStat(trackStatMqVo);
                    }
                } catch (Exception e) {
                    //出现异常,将key删除,保证下次消息能消费
                    redisTemplate.delete(trackStatMqVo.getBusinessNo());
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
